package com.mukefile.service.impl;

import com.mukefile.dao.ShareFileDao;
import com.mukefile.pojo.Manager;
import com.mukefile.pojo.ShareFile;
import com.mukefile.service.ShareFileService;
import com.mukefile.utils.GetPathProperties;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.FieldResult;
import javax.persistence.GeneratedValue;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * @Author: kenewstar
 * @Description:
 * @Date:Created in 2020/5/7
 */
@Service("shareFileService")
@Transactional(rollbackFor = Exception.class)
public class ShareFileServiceImpl implements ShareFileService {

    @Autowired
    private ShareFileDao shareFileDao;
    @Autowired
    private GetPathProperties getPathProperties;
    @Override
    public List<ShareFile> showAllShareFile() {
        List<ShareFile> list = this.shareFileDao.selectAllShareFile();
        return list;
    }

    @Override
    public int deleteFile(Integer fid, String fileName, Manager manager) {
        int i = this.shareFileDao.deleteFile(fid);
        if (i==0){
            return 0;
        }
        //获取路径
        String path = this.getPathProperties.getUploadPath();
        File file = new File(path+File.separator+fileName);
        if (file.exists()){
            //文件存在
            file.delete();
        }
        return 1;
    }

    @Override
    public int fileUpload(ShareFile shareFile,File file,Manager manager) {
        int i = this.shareFileDao.fileUpload(shareFile);
        if (i==0){
            return 0;
        }
        //获取路径
        String path = this.getPathProperties.getUploadPath();
        File destFile = new File(path+File.separator+shareFile.getFileName());
        if (!destFile.exists()){
            //文件存在
            try {
                FileUtils.copyFile(file,destFile);
            } catch (IOException e) {
                return 0;
            }
        }
        return 1;
    }
}

